package com.llollox.openharmonyprojects.compoundbuttongroupsample;

import com.llollox.openharmonyprojects.compoundbuttongroup.CompoundButtonGroup;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.global.resource.Element;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.utils.PacMap;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by lorenzorigato
 */
public class CompoundButtonGroupFragment extends Fraction {
    private static final String TAG = "CompoundButtonGroupFragment";
    // PLANETS array should match PLANETS array in library's CompoundButtonGroup class
    private static final String[] PLANETS = {"Mercury", "Pluto", "Saturn", "Earth",
            "Venus", "Neptune", "Uranus", "Mars", "Jupiter", "Sun", "Mercury1", "Pluto1", "Saturn1",
            "Earth1", "Venus1", "Neptune1", "Uranus1", "Mars1", "Jupiter1", "Sun1"};
    private static PacMap mArgument;
    private ComponentContainer mComponentContainer;
    private CompoundButtonGroup compoundButtonGroup;

    private static PacMap getArgument() {
        return mArgument;
    }

    private static void setArgument(PacMap value) {
        mArgument = value;
    }

    /**
     * API to get instance of this class
     *
     * @param layoutId which xml resource to load
     * @return instance of fraction
     */
    public static CompoundButtonGroupFragment newInstance(int layoutId) {
        PacMap args = new PacMap();
        args.putIntValue(Argument.LAYOUT_ID, layoutId);
        setArgument(args);
        CompoundButtonGroupFragment compoundButtonGroupFragment = new CompoundButtonGroupFragment();
        return compoundButtonGroupFragment;
    }

    /**
     * get the String array
     *
     * @param context the context
     * @param id      the id
     * @return String array value
     */
    public static String[] getStrArray(Context context, int id) {
        String[] result = null;
        if (context != null) {
            ResourceManager manager = context.getResourceManager();
            if (manager != null) {
                try {
                    result = manager.getElement(id).getStringArray();
                } catch (IOException | NotExistException | WrongTypeException err) {
                    LogUtil.error(TAG, "Error in getStrArray : "+ err.toString());
                }
            }
        }
        return result;
    }

    private Element getElement(Context context) {
        ohos.global.resource.Element element = null;
        try {
            element = context.getResourceManager().getElement(ResourceTable.String_planets);
        } catch (NotExistException | WrongTypeException | IOException exe) {
            LogUtil.error(TAG, "Exception in getElement " + exe.toString());
        }
        return element;
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        int layoutId = -1;
        if (getArgument() != null && getArgument().hasKey(Argument.LAYOUT_ID)) {
            layoutId = getArgument().getIntValue(Argument.LAYOUT_ID);
        } else {
            LogUtil.error(TAG, "A compound button group fragment requires a layout id as argument");
        }

        LayoutScatter layoutInflater = LayoutScatter.getInstance(getFractionAbility());

        DependentLayout relativeLayout = (DependentLayout) layoutInflater.parse(
                ResourceTable.Layout_compound_button_group_fragment, container, false);

        compoundButtonGroup = (CompoundButtonGroup) layoutInflater.parse(layoutId, relativeLayout, false);

        DependentLayout.LayoutConfig params = (DependentLayout.LayoutConfig) compoundButtonGroup.getLayoutConfig();
        params.addRule(DependentLayout.LayoutConfig.ALIGN_TOP);
        params.addRule(DependentLayout.LayoutConfig.ABOVE, ResourceTable.Id_get_value_btn);

        compoundButtonGroup.setOnButtonSelectedListener(new CompoundButtonGroup.OnButtonSelectedListener() {
            @Override
            public void onButtonSelected(int position, String value, boolean isChecked) {
                String checked = getFractionAbility().getString(isChecked ? ResourceTable.String_checked
                        : ResourceTable.String_unchecked);
                showToast(checked + ": " + value, getFractionAbility());
            }
        });
        Button getValueBtn = (Button) relativeLayout.findComponentById(ResourceTable.Id_get_value_btn);
        getValueBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String checked = getFractionAbility().getString(ResourceTable.String_checked);
                ArrayList<String> checkedPlanets = new ArrayList<>();
                for (int position : compoundButtonGroup.getCheckedPositions()) {
                    checkedPlanets.add(PLANETS[position]);
                }
                showToast(checked + ": " + String.valueOf(checkedPlanets), getFractionAbility());
            }
        });
        relativeLayout.addComponent(compoundButtonGroup, 0);
        compoundButtonGroup.setEntries(PLANETS);
        return relativeLayout;
    }

    @Override
    protected void onComponentDetach() {
        super.onComponentDetach();
    }

    private void showToast(String msg, FractionAbility context) {
        ToastDialog toastDialog = new ToastDialog(context);
        toastDialog.setAutoClosable(false);
        toastDialog.setContentText(msg);
        toastDialog.show();
    }

    private static class Argument {
        private static final String LAYOUT_ID = "layoutId";
    }
}
